package com.daguchuangyi.erp_android.util;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.daguchuangyi.erp_android.ErpApplication;
import com.daguchuangyi.erp_android.login.LoginActivity;
import com.daguchuangyi.erp_android.model.error.ErrorMsgModel;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jude.utils.JUtils;

import retrofit2.HttpException;

/**
 * Created by lijianjian on 2018/4/9.
 */

public class ErrorHandler {
    private static final String TAG = "ErrorHandler";
    public static void handlerNetworError(Throwable throwable, String defaultErrorMsg) {

        if (throwable instanceof HttpException) {
            HttpException httpException = (HttpException) throwable;
            try {
                String errorBody = httpException.response().errorBody().string();
                JUtils.Log("errorBody is : " + errorBody);
                Gson gson = new GsonBuilder().create();
                ErrorMsgModel mError = gson.fromJson(errorBody, ErrorMsgModel.class);
                JUtils.ToastLong(mError.getMsg());
            } catch (Exception e) {
                JUtils.ToastLong("加载数据出错:" + throwable.getMessage());
                JUtils.Log("error msg : " + e.getMessage());
                e.printStackTrace();
            } finally {
                if (httpException.code() == 401) {
                    Intent intent = new Intent(ErpApplication.getAppContext(), LoginActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    ErpApplication.getAppContext().startActivity(intent);
                }
            }
        } else {
            if (!TextUtils.isEmpty(defaultErrorMsg)) {
                JUtils.ToastLong(defaultErrorMsg);
            }
            Log.e(TAG, "net work error.");
            throwable.printStackTrace();
        }
    }
}
